package com.daffodil.devtool.config;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExtProperties;

import com.daffodil.devtool.entity.GenTemplate;
import com.daffodil.devtool.service.IGenTemplateService;
import com.daffodil.util.SpringBeanUtils;
import com.daffodil.util.StringUtils;

/**
 * 
 * @author yweijian
 * @date 2023年8月7日
 * @version 2.0.0
 * @copyright Copyright 2020-2023 www.daffodilcloud.com.cn
 * @description
 */
public class TemplateResourceLoader extends ResourceLoader {

    private static IGenTemplateService templateService;

    @Override
    public Reader getResourceReader(String source, String encoding) throws ResourceNotFoundException {
        GenTemplate template = templateService.selectEntityById(source);
        if(StringUtils.isNull(template)) {
            throw new ResourceNotFoundException("目标资源模板不存在");
        }
        InputStream inputStream = IOUtils.toInputStream(template.getContent(), StandardCharsets.UTF_8);
        return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    }

    @Override
    public boolean isSourceModified(Resource resource) {
        return false;
    }

    @Override
    public long getLastModified(Resource resource) {
        return 0;
    }

    @Override
    public void init(ExtProperties configuration) {
        templateService = SpringBeanUtils.getBean(IGenTemplateService.class);
    }

}
